#!/usr/bin/env bash
set -euo pipefail

SCRIPT_PATH=$(dirname "$0")
TEMPORARY_DIR=$(mktemp -d)

OUTPUT_PATH="${SCRIPT_PATH}/../Sources/MapboxSearch/PublicAPI/Maki.swift"
GENERATED_MAKI_OUTPUT_PATH="${SCRIPT_PATH}/../Sources/MapboxSearchUI/Assets.xcassets/maki/"
PREV_GENERATED_MAKI_OUTPUT_PATH="${TEMPORARY_DIR}/prev_maki/"

GENERATED_PNG_OUTPUT_SIZE_PT=24
GENERATED_PNG_NONE_BORDER_WIDTH_PT=0

# Pass DEBUG=1 to get diffs for non-equal images
DEBUG="${DEBUG:-0}"


echo "Downloading latest Maki"
pushd "${TEMPORARY_DIR}" > /dev/null
curl --silent -Lo maki.zip https://github.com/mapbox/maki/archive/refs/heads/main.zip

echo "Unzipping Maki.zip"
unzip -o maki.zip -d maki > /dev/null

echo "Maki.swift generation"
cat <<EOF > "${OUTPUT_PATH}"
// This file was generated by '$(basename $0)' script

// swiftformat:disable:next redundantRawValues
/// Represents static enumeration for all available icons in Mapbox [Maki icon set](https://github.com/mapbox/maki/).
/// Kebab-case was replaced with camelCase.
public enum Maki: String, CaseIterable, Codable {
EOF

MAKI_ICON_PATHS=$(find maki/*/icons -name "*.svg" | sort)

i=0
for file in ${MAKI_ICON_PATHS}; do
    filefolder=$(dirname "$file")
    filename=$(basename "$file" .svg)
    # snake_case to camelCase: https://stackoverflow.com/a/50224830
    camelName=$(echo ${filename//-/_} | perl -nE 'say lcfirst join "", map {ucfirst lc} split /[^[:alnum:]]+/')
    echo "    /// Maki icon \"${filename}\"" >> "${OUTPUT_PATH}"
    echo "    case ${camelName} = \"${filename}\"" >> "${OUTPUT_PATH}"
    i=$((i+1))
done

cat <<EOF >> "${OUTPUT_PATH}"

    /// Original name used in Maki icon set
    public var name: String { rawValue }
}
EOF


echo "Validate Maki.swift"
swiftc "${OUTPUT_PATH}" -o /dev/null


echo "Copying SVG sources"
copy_svg_sources() {
    # Clean xcassets Maki
    mv "$GENERATED_MAKI_OUTPUT_PATH" "$PREV_GENERATED_MAKI_OUTPUT_PATH"

    for file in ${MAKI_ICON_PATHS}; do
        filefolder=$(dirname "$file")
        filename=$(basename "$file" .svg)

        local CURRENT_ICON_IMAGESET_OUTPUT_PATH="${GENERATED_MAKI_OUTPUT_PATH}/${filename}.imageset/"
        mkdir -p "${CURRENT_ICON_IMAGESET_OUTPUT_PATH}"

        mv ${file} ${CURRENT_ICON_IMAGESET_OUTPUT_PATH}

        IMAGESET_CONTENT_JSON='{"images":[{"filename":"'"${filename}"'.svg","idiom":"universal"}],"info":{"author":"xcode","version":1},"properties":{"preserves-vector-representation":true}}'
        echo "${IMAGESET_CONTENT_JSON}" > "${CURRENT_ICON_IMAGESET_OUTPUT_PATH}/Contents.json"
    done
}
copy_svg_sources

echo "Done. Number of icons: $i"
